<?php
/**********************************************************************
 *                                                                    *    
 * Copyright (c) 2009 Dmytro Bezhnar. All rights reserved.     *
 *                                                                    *
 **********************************************************************/

/**
 * Base class for all persistble entity managers.
 * It's DAO-less for simplicity.
 *
 * @author 
 * @version $Id: ORMManager.php,v 1.1 2008/10/15 06:36:58 demonit Exp $
 */
class ORMManager extends AbstractManager
{
	/**
	 * @var Doctrine_Cache_Memcache
	 */
	
	public static $cacheDriver;
	
	/**
     * Doctrine_Connection connection
     * @var Doctrine_Connection
     */
    protected $orm_connection = null;
   
    /**
     * Constructor
     */
    function __construct() {
        global $options,$orm_connection,$profiler;
        if (!is_object($orm_connection)){
            require_once "../../core2/lib/Doctrine.php";
           
            if ($options['database_details']['dbdriver'] == ''){
                $options['database_details']['dbdriver'] = 'mysql';
            }
            
        	$db_dsn = $options['database_details']['dbdriver'] .
                         '://' . $options['database_details']['username'] .
                         ':' . $options['database_details']['password'] .
                         '@' . $options['database_details']['hostname'] .
                         ':' . $options['database_details']['port'] .
                         '/' . $options['database_details']['database'];
            
            try {
                $orm_connection = Doctrine_Manager::connection($db_dsn, 'main_connection');
                //$debugger = new DebugProfilerListener();
				//$orm_connection->addListener($debugger);
			
				$profiler = new Doctrine_Connection_Profiler();
				$orm_connection->setListener($profiler);
					
				
                $orm_connection->setCharset($options['locale']['db_charset']);
            
                $this->orm_connection = $orm_connection;
                $orm_connection->setAttribute(Doctrine::ATTR_VALIDATE, Doctrine::VALIDATE_ALL);
                $orm_connection->setAttribute(Doctrine::ATTR_QUERY_LIMIT, Doctrine::LIMIT_ROWS);
                $orm_connection->setAttribute(Doctrine::ATTR_USE_DQL_CALLBACKS, true);
                if ($options['memcache']['enable']) {
                    if ($options['memcache']['time_query_cache'] == ''){
                        $options['memcache']['time_query_cache'] = 5;
                    }
                    if ($options['memcache']['time_result_cache'] == ''){
                        $options['memcache']['time_result_cache'] = 5;
                    }
                    $servers = array('host' => $options['memcache']['host'],
                                     'port' => $options['memcache']['port'],
                                     'persistent' => false);
                    self::$cacheDriver = new Doctrine_Cache_Memcache(array('servers' => $servers,
                                           'compression' => false));
                    $orm_connection->setAttribute(Doctrine::ATTR_QUERY_CACHE, self::$cacheDriver);
                    $orm_connection->setAttribute(Doctrine::ATTR_QUERY_CACHE_LIFESPAN, $options['memcache']['time_query_cache']);
                    $orm_connection->setAttribute(Doctrine::ATTR_RESULT_CACHE, self::$cacheDriver);
                    $orm_connection->setAttribute(Doctrine::ATTR_RESULT_CACHE_LIFESPAN,$options['memcache']['time_result_cache']);
                }
                
                Doctrine_Manager::getInstance()->setAttribute( 'model_loading', 'conservative');
                
                //Doctrine::loadModels(array('../application/managers/orm','../../core2/classes/managers/orm'));
                //print $orm_connection->getName();
            }catch (Doctrine_Connection_Exception $e) {
                $this->trigger_error($e->__toString() , E_USER_ERROR);
            }
        }else{
            $this->orm_connection = $orm_connection;
        }
    }
    
    /**
     * Get the Doctrine_Table object for the passed model
     *
     * @param string $componentName
     * @return Doctrine_Table
     */
    
    public function getTable($table){
        return Doctrine::getTable($table);
    }
    
    
    /**
	 * Make memcache name
	 * @param string $qs
	 * @param string $name
	 */
    public static function getMemcacheName($qs,$name) {
    	if ($name!='') {
    		$key = $name;
    	} else{
    		$key = $GLOBALS['options']['memcache']['name'].'_'.crc32($qs); 
    	}
    	return $key.'_'.$_SESSION['lang_mysql_charset'];        
    }  
    
    /**
     * create
     * returns a new Doctrine_Query object
     *
     * @param Doctrine_Connection $conn     optional connection parameter
     * @return Doctrine_Query
     */
    
    public function getQuery($conn = null){
        return Doctrine_Query::create($conn);
    }
 
    /**
     * getAssArray()
     * this is method is used by the get Associate array
     *
     * @param mixed $result Array or Doctrine_Collection
     * @param string $key_field
     * @param string $item_field
     * @return array .
     * 
     */
    
    public function getAssArray($result,$key_field,$item_field){
    	$array = array();
    	if (is_object($result)){
    		foreach ($result as $item){
    			$array[$item->$key_field] = $item->$item_field;
    		}
    	}elseif (is_array($result)){
    		foreach ($result as $item){
    			$array[$item[$key_field]] = $item[$item_field];
    		}
    	}
    	return $array;
    }
    
    /**
     * Get the current connection instance
     *
     * @throws Doctrine_Connection_Exception       if there are no open connections
     * @return Doctrine_Connection
     */
    
    public function getCurrentConnection(){
    	$manager = Doctrine_Manager::getInstance();
    	return $manager->getCurrentConnection();
    }
    
	public function checkTextForMysql($text,$strip_tags=true) {
       if ($strip_tags) { $text = strip_tags($text); }
#    return mysql_real_escape_string($text);
      $pattern[0]="/\\x00/";
  	  $pattern[1]='/\x5c/';
  	  $pattern[2]="/'/";
      $pattern[3]="/\x1a/";
      $pattern[4]="/\"/";
      $replacement[0]="\\x00";
      $replacement[1]="\\\\\\\\";
       $replacement[2]="\'";
      $replacement[3]="\\x1a";
      $replacement[4]="\"";
      $text=preg_replace($pattern, $replacement, $text);
     return $text;
    }
}

?>